﻿
var calendarUrl = "/Handlers/CalendarHandler.asmx/GetDaysByGroup";

$(function () {
    $('.calendar-moths > div').click(function () {
        displayCalendar($(this).attr('month'), $(this).attr('year'));
    });
});

function displayCalendar(month, year) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: calendarUrl,
        data: calendarGetData(month, year),
        dataType: "json",
        beforeSend: function () {
            $('.calendar-moths > div').removeClass('red').each(function () {
                $(this).text($(this).attr('unselected-month'));
            });
            clearCalendar();
        },
        success: function (x) {
            buildCalendar(x);
            var selectedMonth = $('.calendar-moths > div[year=' + year + '][month=' + month + ']');
            selectedMonth.addClass('red').text(selectedMonth.attr('selected-month'));
        }
    });
}

function calendarGetData(month, year) {
    return "{'month':" + month + ",'year':" + year + "}";
}

function clearCalendar() {
    $('.cal-tab .cal-tr:not(.cal-head) .cal-td').each(function () {
        $(this).attr('class', 'cal-td cal-td-empty').text('');
    });
}

function buildCalendar(d) {
    for (var xd = 0; xd < d['d']['Days'].length; xd++) {
        $('.cal-tab .cal-tr:not(.cal-head):eq(' + (d['d']['Days'][xd]['Week'] - 1) + ')')
                .find('.cal-td:eq(' + d['d']['Days'][xd]['DayOfWeek'] + ')')
                .removeClass('cal-td-empty')
                .addClass('cal-td-type' + d['d']['Days'][xd]['Type'])
                .text(d['d']['Days'][xd]['Day'] + '/' + d['d']['Days'][xd]['NextDay']);
    }
}
